<script setup>
	import { ref, reactive } from 'vue'
	import userApi from '@/utils/apis/user.js'
	import { useUserStore } from '@/stores/users.js'
	const userStore = useUserStore()
	// 表单数据
	const formData = ref({
		account: '12345678',
		password: '123456',
	})
	const formRef = ref()
	// 定义表单数据验证规则
	const accountRules = ref({
		account: {
			rules: [
				{ required: true, errorMessage: '请输入登录账号' },
				{
					pattern: '^[a-zA-Z0-9]{6,8}$',
					errorMessage: '登录账号格式不正确',
				},
			],
		},
		password: {
			rules: [
				{ required: true, errorMessage: '请输入登录密码' },
				{ pattern: '^\\d{6}$', errorMessage: '登录密码格式不正确' },
			],
		},
	})
	// 登录按钮点击事件
	async function onFormSubmit() {
		try {
			// 表单校验
			const formData = await formRef.value.validate()
			// 调用接口
			const { data, code } = await userApi.login(formData)
			// 判断成功
			if (code !== 200) return uni.utils.toast()
			// 持久化token
			userStore.token = data
		} catch (err) {
			console.log(err)
		}
	}
</script>
<template>
	<uni-forms
		class="login-form"
		ref="formRef"
		:rules="accountRules"
		:model="formData"
	>
		<uni-forms-item name="account">
			<input
				v-model="formData.account"
				type="text"
				placeholder="请输入账号"
				class="uni-input-input"
				placeholder-style="color: #818181"
			/>
		</uni-forms-item>
		<uni-forms-item name="password">
			<input
				v-model="formData.password"
				type="text"
				placeholder="请输入密码"
				class="uni-input-input"
				placeholder-style="color: #818181"
			/>
		</uni-forms-item>
		<button class="submit-button" @click="onFormSubmit">登录</button>
	</uni-forms>
</template>

<style lang="scss" scoped>
	@import './styles.scss';
</style>
